package com.ruoyi.system.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Random;

/**
 * 阿里云短信服务
 * 
 * @author ruoyi
 */
@Slf4j
@Service
public class AliyunSmsService {

    @Value("${aliyun.sms.access-key-id:}")
    private String accessKeyId;

    @Value("${aliyun.sms.access-key-secret:}")
    private String accessKeySecret;

    @Value("${aliyun.sms.endpoint:dysmsapi.aliyuncs.com}")
    private String endpoint;

    @Value("${aliyun.sms.sign-name:}")
    private String signName;

    @Value("${aliyun.sms.template-code:}")
    private String templateCode;

    @Value("${aliyun.sms.enabled:false}")
    private boolean smsEnabled;

    private Client client;

    @PostConstruct
    public void init() {
        if (!smsEnabled) {
            log.info("短信验证码功能已禁用，跳过阿里云短信服务初始化");
            return;
        }
        
        try {
            Config config = new Config()
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret)
                    .setEndpoint(endpoint);
            this.client = new Client(config);
            log.info("阿里云短信服务初始化成功");
        } catch (Exception e) {
            log.error("阿里云短信服务初始化失败", e);
            throw new ServiceException("短信服务初始化失败");
        }
    }

    /**
     * 发送短信验证码
     * 
     * @param phoneNumber 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendSmsCode(String phoneNumber, String code) {
        if (!smsEnabled) {
            log.warn("短信验证码功能已禁用，跳过发送短信");
            return false;
        }
        
        try {
            if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) {
                log.warn("阿里云短信配置未完成，跳过发送短信");
                return false;
            }

            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            SendSmsResponse response = client.sendSms(request);
            
            if ("OK".equals(response.getBody().getCode())) {
                log.info("短信发送成功，手机号：{}，验证码：{}", phoneNumber, code);
                return true;
            } else {
                log.error("短信发送失败，手机号：{}，错误码：{}，错误信息：{}", 
                         phoneNumber, response.getBody().getCode(), response.getBody().getMessage());
                return false;
            }
        } catch (Exception e) {
            log.error("发送短信异常，手机号：{}", phoneNumber, e);
            return false;
        }
    }

    /**
     * 生成6位数字验证码
     * 
     * @return 验证码
     */
    public String generateSmsCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }

    /**
     * 验证手机号格式
     * 
     * @param phoneNumber 手机号
     * @return 是否有效
     */
    public boolean isValidPhoneNumber(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            return false;
        }
        // 简单的手机号格式验证
        return phoneNumber.matches("^1[3-9]\\d{9}$");
    }
}
